// 产量统计路由文件
const express = require('express');
const sql = require('mssql');
const router = express.Router();

// 格式化日期为 YYYY-MM-DD
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 格式化日期时间为 YYYY-MM-DD HH:mm:ss
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 格式化时间范围标签
function formatTimeRangeLabel(start, end, includeDate = false) {
  const startHour = String(start.getHours()).padStart(2, '0');
  const endHour = String(end.getHours()).padStart(2, '0');
  if (includeDate) {
    const dateStr = formatDate(start);
    return `${dateStr} ${startHour}:00-${endHour}:00`;
  }
  return `${startHour}:00-${endHour}:00`;
}

// 计算所有需要的时间区间
function calculateTimeRanges() {
  const now = new Date();
  const ranges = {
    yesterdayDayShift: { start: null, end: null, intervals: [] },
    yesterdayNightShift: { start: null, end: null, intervals: [] },
    currentShift: { start: null, end: null, intervals: [] },
    currentShiftIntervals: []
  };
  
  const currentHour = now.getHours();
  const isCurrentShiftDay = currentHour >= 8 && currentHour < 20;
  
  // 前一天日期
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  
  // 1. 前一天白班 (8:00-20:00)
  ranges.yesterdayDayShift.start = new Date(yesterday);
  ranges.yesterdayDayShift.start.setHours(8, 0, 0, 0);
  ranges.yesterdayDayShift.end = new Date(yesterday);
  ranges.yesterdayDayShift.end.setHours(20, 0, 0, 0);
  
  // 为前一天白班添加2小时间隔
  for (let h = 8; h < 20; h += 2) {
    const intervalStart = new Date(yesterday);
    intervalStart.setHours(h, 0, 0, 0);
    const intervalEnd = new Date(yesterday);
    intervalEnd.setHours(h + 2, 0, 0, 0);
    
    ranges.yesterdayDayShift.intervals.push({
      startTime: intervalStart,
      endTime: intervalEnd,
      label: formatTimeRangeLabel(intervalStart, intervalEnd, true)
    });
  }
  
  // 2. 前一天夜班 (20:00-次日8:00)
  ranges.yesterdayNightShift.start = new Date(yesterday);
  ranges.yesterdayNightShift.start.setHours(20, 0, 0, 0);
  ranges.yesterdayNightShift.end = new Date(yesterday);
  ranges.yesterdayNightShift.end.setDate(ranges.yesterdayNightShift.end.getDate() + 1);
  ranges.yesterdayNightShift.end.setHours(8, 0, 0, 0);
  
  // 为前一天夜班添加2小时间隔
  // 夜班第一部分 (20:00-24:00)
  for (let h = 20; h < 24; h += 2) {
    const intervalStart = new Date(yesterday);
    intervalStart.setHours(h, 0, 0, 0);
    const intervalEnd = new Date(yesterday);
    intervalEnd.setHours(h + 2, 0, 0, 0);
    
    ranges.yesterdayNightShift.intervals.push({
      startTime: intervalStart,
      endTime: intervalEnd,
      label: formatTimeRangeLabel(intervalStart, intervalEnd, true)
    });
  }
  
  // 夜班第二部分 (0:00-8:00)
  for (let h = 0; h < 8; h += 2) {
    const intervalStart = new Date(yesterday);
    intervalStart.setDate(intervalStart.getDate() + 1);
    intervalStart.setHours(h, 0, 0, 0);
    const intervalEnd = new Date(yesterday);
    intervalEnd.setDate(intervalEnd.getDate() + 1);
    intervalEnd.setHours(h + 2, 0, 0, 0);
    
    ranges.yesterdayNightShift.intervals.push({
      startTime: intervalStart,
      endTime: intervalEnd,
      label: formatTimeRangeLabel(intervalStart, intervalEnd, true)
    });
  }
  
  // 3. 当前班次
  if (isCurrentShiftDay) {
    // 当前白班 (8:00-20:00)
    ranges.currentShift.start = new Date(now);
    ranges.currentShift.start.setHours(8, 0, 0, 0);
    ranges.currentShift.end = new Date(now);
    ranges.currentShift.end.setHours(20, 0, 0, 0);
    
    // 为当前白班添加2小时间隔
    for (let h = 8; h < 20; h += 2) {
      const intervalStart = new Date(now);
      intervalStart.setHours(h, 0, 0, 0);
      const intervalEnd = new Date(now);
      intervalEnd.setHours(h + 2, 0, 0, 0);
      
      // 使用完整的2小时区间作为查询范围，不截止到当前时间
      ranges.currentShift.intervals.push({
        startTime: intervalStart,
        endTime: intervalEnd, // 使用完整的结束时间
        originalEndTime: intervalEnd, // 保存原始结束时间用于生成完整标签
        label: formatTimeRangeLabel(intervalStart, intervalEnd) // 使用完整区间生成标签
      });
      
      // 添加所有区间到当前班次间隔中，包括未开始的区间
      ranges.currentShiftIntervals.push({
        startTime: intervalStart,
        endTime: intervalEnd, // 使用完整的结束时间
        originalEndTime: intervalEnd, // 保存原始结束时间用于生成完整标签
        label: formatTimeRangeLabel(intervalStart, intervalEnd) // 使用完整区间生成标签
      });
    }
  } else {
    // 当前夜班 (20:00-次日8:00)
    if (currentHour < 8) {
      // 凌晨时间，夜班起始于前一天20:00
      ranges.currentShift.start = new Date(now);
      ranges.currentShift.start.setDate(ranges.currentShift.start.getDate() - 1);
      ranges.currentShift.start.setHours(20, 0, 0, 0);
    } else {
      // 晚上20点之后，夜班起始于当天20:00
      ranges.currentShift.start = new Date(now);
      ranges.currentShift.start.setHours(20, 0, 0, 0);
    }
    
    ranges.currentShift.end = new Date(ranges.currentShift.start);
    ranges.currentShift.end.setDate(ranges.currentShift.end.getDate() + 1);
    ranges.currentShift.end.setHours(8, 0, 0, 0);
    
    // 为当前夜班添加2小时间隔
    const startDate = new Date(ranges.currentShift.start);
    
    // 夜班第一部分 (20:00-24:00)
    for (let h = 20; h < 24; h += 2) {
      const intervalStart = new Date(startDate);
      intervalStart.setHours(h, 0, 0, 0);
      const intervalEnd = new Date(startDate);
      intervalEnd.setHours(h + 2, 0, 0, 0);
      
      // 使用完整的2小时区间作为查询范围，不截止到当前时间
      ranges.currentShift.intervals.push({
        startTime: intervalStart,
        endTime: intervalEnd, // 使用完整的结束时间
        originalEndTime: intervalEnd, // 保存原始结束时间用于生成完整标签
        label: formatTimeRangeLabel(intervalStart, intervalEnd) // 使用完整区间生成标签
      });
      
      // 添加所有区间到当前班次间隔中，包括未开始的区间
      ranges.currentShiftIntervals.push({
        startTime: intervalStart,
        endTime: intervalEnd, // 使用完整的结束时间
        originalEndTime: intervalEnd, // 保存原始结束时间用于生成完整标签
        label: formatTimeRangeLabel(intervalStart, intervalEnd) // 使用完整区间生成标签
      });
    }
    
    // 夜班第二部分 (0:00-8:00)
    const nextDay = new Date(startDate);
    nextDay.setDate(nextDay.getDate() + 1);
    
    for (let h = 0; h < 8; h += 2) {
      const intervalStart = new Date(nextDay);
      intervalStart.setHours(h, 0, 0, 0);
      const intervalEnd = new Date(nextDay);
      intervalEnd.setHours(h + 2, 0, 0, 0);
      
      // 使用完整的2小时区间作为查询范围，不截止到当前时间
      ranges.currentShift.intervals.push({
        startTime: intervalStart,
        endTime: intervalEnd, // 使用完整的结束时间
        originalEndTime: intervalEnd, // 保存原始结束时间用于生成完整标签
        label: formatTimeRangeLabel(intervalStart, intervalEnd) // 使用完整区间生成标签
      });
      
      // 添加所有区间到当前班次间隔中，包括未开始的区间
      ranges.currentShiftIntervals.push({
        startTime: intervalStart,
        endTime: intervalEnd, // 使用完整的结束时间
        originalEndTime: intervalEnd, // 保存原始结束时间用于生成完整标签
        label: formatTimeRangeLabel(intervalStart, intervalEnd) // 使用完整区间生成标签
      });
    }
  }
  
  return ranges;
}

// 保留第一个formatDateTime函数，删除重复的UTC版本
// 使用本地时间确保与数据库中的时间一致

// 获取指定时间区间的产量数据
async function getProductionData(pool, startTime, endTime, lineId, stepName) {
  console.log('===== getProductionData 被调用 =====');
  console.log('参数:', { startTime, endTime, lineId, stepName });
  
  // 判断是否为特殊查询（不使用DISTINCT）
  const useNonDistinct = stepName === 'NO_DISTINCT';
  const actualStepName = stepName === 'NO_DISTINCT' ? 'DC' : stepName;
  
  // 修改SQL查询以适应VarChar类型的时间参数
  const query = `
    SELECT 
      COUNT(DISTINCT wlh.lot_id) as count
    FROM 
      (
        SELECT DISTINCT lot_id, equipment_id, trans_type, TRANS_TIME, STEP_NAME
        FROM mes_db.mes_db.dbo.wip_lot_his
        WHERE trans_type IN ('TRACKMOVE', 'SKIPLOT')
        AND CONVERT(VARCHAR(19), TRANS_TIME, 120) BETWEEN @startTime AND @endTime
        AND STEP_NAME = @stepName
      ) wlh
      LEFT JOIN stg_mes_ras_eqp e ON wlh.equipment_id = e.equipment_id
      LEFT JOIN stg_mes_ras_eqp_line el ON e.EQUIPMENT_ID = el.EQUIPMENT_ID
    WHERE 
      @lineId = '' OR el.LINE_ID = @lineId
  `;
  try {
      // 确保startTime总是小于endTime，处理时区和时间比较问题
      const startTimestamp = startTime.getTime();
      const endTimestamp = endTime.getTime();
      const validStartTime = startTimestamp < endTimestamp ? startTime : endTime;
      const validEndTime = startTimestamp < endTimestamp ? endTime : startTime;
      
      console.log('执行数据库查询:');
      console.log('- 时间范围:', formatDateTime(validStartTime), '到', formatDateTime(validEndTime));
      console.log('- 产线ID:', lineId || '空');
      console.log('- 工序:', actualStepName);
      
      // 转换时间格式为'YYYY-MM-DD HH:MM:SS'
      const formatToSqlDateTime = (date) => {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };

      const request = pool.request();
      request.input('startTime', sql.VarChar, formatToSqlDateTime(validStartTime));
      request.input('endTime', sql.VarChar, formatToSqlDateTime(validEndTime));
      request.input('lineId', sql.VarChar, lineId || '');
      request.input('stepName', sql.VarChar, actualStepName);
      const result = await request.query(query);
      
      const count = result.recordset[0]?.count || 0;
      console.log(`查询结果: ${count} 条记录`);
      console.log('===== getProductionData 结束 =====');
      
      return count;
    } catch (error) {
      console.error('===== 查询错误 =====');
      console.error(`错误信息:`, error.message);
      console.error(`错误详情:`, error);
      console.error(`时间区间: ${formatDateTime(startTime)} 到 ${formatDateTime(endTime)}`);
      return 0;
    }
}

// 根路由处理
router.get('/', async (req, res) => {
  // 重定向到statistics路由或直接调用相同逻辑
  const { lineId, STEP_NAME = 'DC' } = req.query;
  
  try {
    // 计算时间区间
    const timeRanges = calculateTimeRanges();
    
    // 计算上上个班次的时间（当前时间的上上个班次）
    const now = new Date();
    const currentHour = now.getHours();
    const twoDaysAgoShift = {
      start: null,
      end: null
    };
    const yesterdayShift = {
      start: null,
      end: null
    };
    
    // 计算时间
    if (currentHour >= 8 && currentHour < 20) {
      // 当前是白班 (8:00-20:00)
      // 上上个班次：前一天的白班 (8:00-20:00)
      twoDaysAgoShift.start = new Date(now);
      twoDaysAgoShift.start.setDate(twoDaysAgoShift.start.getDate() - 1);
      twoDaysAgoShift.start.setHours(8, 0, 0, 0);
      twoDaysAgoShift.end = new Date(now);
      twoDaysAgoShift.end.setDate(twoDaysAgoShift.end.getDate() - 1);
      twoDaysAgoShift.end.setHours(20, 0, 0, 0);
      
      // 上个班次：前一天的夜班 (20:00-次日8:00)
      yesterdayShift.start = new Date(now);
      yesterdayShift.start.setDate(yesterdayShift.start.getDate() - 1);
      yesterdayShift.start.setHours(20, 0, 0, 0);
      yesterdayShift.end = new Date(now);
      yesterdayShift.end.setHours(8, 0, 0, 0);
    } else if (currentHour >= 20) {
      // 当前是夜班 (20:00-次日8:00)
      // 上上个班次：当天的白班 (8:00-20:00)
      twoDaysAgoShift.start = new Date(now);
      twoDaysAgoShift.start.setHours(8, 0, 0, 0);
      twoDaysAgoShift.end = new Date(now);
      twoDaysAgoShift.end.setHours(20, 0, 0, 0);
      
      // 上个班次：前一天的夜班 (20:00-次日8:00)
      yesterdayShift.start = new Date(now);
      yesterdayShift.start.setDate(yesterdayShift.start.getDate() - 1);
      yesterdayShift.start.setHours(20, 0, 0, 0);
      yesterdayShift.end = new Date(now);
      yesterdayShift.end.setHours(8, 0, 0, 0);
    } else {
      // 当前是凌晨 (0:00-8:00)
      // 上上个班次：前天的白班 (8:00-20:00)
      twoDaysAgoShift.start = new Date(now);
      twoDaysAgoShift.start.setDate(twoDaysAgoShift.start.getDate() - 2);
      twoDaysAgoShift.start.setHours(8, 0, 0, 0);
      twoDaysAgoShift.end = new Date(now);
      twoDaysAgoShift.end.setDate(twoDaysAgoShift.end.getDate() - 2);
      twoDaysAgoShift.end.setHours(20, 0, 0, 0);
      
      // 上个班次：前天的夜班 (20:00-昨天8:00)
      yesterdayShift.start = new Date(now);
      yesterdayShift.start.setDate(yesterdayShift.start.getDate() - 2);
      yesterdayShift.start.setHours(20, 0, 0, 0);
      yesterdayShift.end = new Date(now);
      yesterdayShift.end.setDate(yesterdayShift.end.getDate() - 1);
      yesterdayShift.end.setHours(8, 0, 0, 0);
    }
    
    // 创建数据库连接
    const pool = await sql.connect();
    
    // 查询各个班次的总产量 - 默认使用COUNT(DISTINCT)
    const twoDaysAgoShiftTotal = await getProductionData(
      pool, 
      twoDaysAgoShift.start, 
      twoDaysAgoShift.end,
      lineId, 
      STEP_NAME
    );
    
    const yesterdayShiftTotal = await getProductionData(
      pool, 
      yesterdayShift.start, 
      yesterdayShift.end,
      lineId, 
      STEP_NAME
    );
    
    const currentShiftTotal = await getProductionData(
      pool, 
      timeRanges.currentShift.start, 
      timeRanges.currentShift.end,
      lineId, 
      STEP_NAME
    );
    
    // 为当前班次的所有interval添加count属性 - 只有当前班次需要两小时一查询
    for (const interval of timeRanges.currentShift.intervals) {
      const count = await getProductionData(
        pool, 
        interval.startTime, 
        interval.endTime,
        lineId, 
        STEP_NAME
      );
      interval.count = count;
    }
    
    // 仍然保留currentShiftIntervals数组以备其他用途
    const currentShiftIntervals = timeRanges.currentShiftIntervals.map(interval => {
      const found = timeRanges.currentShift.intervals.find(
        i => i.startTime.getTime() === interval.startTime.getTime()
      );
      return {
        ...interval,
        count: found ? found.count : 0
      };
    });
    
    // 对于其他班次，创建空的intervals数组，因为不需要两小时一查询
    const yesterdayDayShiftIntervals = [];
    const yesterdayNightShiftIntervals = [];
    
    // 获取当前时间判断班次
    const isCurrentShiftDay = currentHour >= 8 && currentHour < 20;
    
    // 构建返回结果 - 按照要求的英文属性名结构
    const result = {
      twoDaysAgoShift: {
          data: twoDaysAgoShiftTotal,
          test: `${formatDate(twoDaysAgoShift.start)}${twoDaysAgoShift.start.getHours() === 8 ? '白班' : '夜班'}`
        },
        yesterdayShift: {
          data: yesterdayShiftTotal,
          test: `${formatDate(yesterdayShift.start)}${yesterdayShift.start.getHours() === 8 ? '白班' : '夜班'}`
        },
      currentShiftTotal: currentShiftTotal,
      currentShiftIntervals: timeRanges.currentShift.intervals.map(interval => {
        // 优先使用原始结束时间生成标签，确保显示完整的2小时间隔
        const startHour = String(interval.startTime.getHours()).padStart(2, '0');
        const endHour = interval.originalEndTime ? 
          String(interval.originalEndTime.getHours()).padStart(2, '0') : 
          String(interval.startTime.getHours() + 2).padStart(2, '0');
        return {
          date: `${startHour}:00-${endHour}:00`,
          data: interval.count || 0
        };
      })
    };
    
    res.json({
      success: true,
      data: result,
      message: '产量统计数据获取成功'
    });
  } catch (error) {
    console.error('获取产量统计数据时出错:', error.message);
    res.status(500).json({
      success: false,
      message: '获取产量统计数据失败',
      error: error.message
    });
  }
});


// 新增路由：执行特定的LotPassRank SQL查询 - 返回与DC一致的数据结构
router.get('/lot-pass-rank', async (req, res) => {
  const { lineId = '', stepName = 'HEL' } = req.query;
  
  try {
    // 计算时间区间 - 与DC路由使用相同的逻辑
    const timeRanges = calculateTimeRanges();
    
    // 计算上上个班次和上个班次的时间
    const now = new Date();
    const currentHour = now.getHours();
    const twoDaysAgoShift = {
      start: null,
      end: null
    };
    const yesterdayShift = {
      start: null,
      end: null
    };
    
    // 计算时间 - 与DC路由使用相同的逻辑
    if (currentHour >= 8 && currentHour < 20) {
      // 当前是白班 (8:00-20:00)
      twoDaysAgoShift.start = new Date(now);
      twoDaysAgoShift.start.setDate(twoDaysAgoShift.start.getDate() - 1);
      twoDaysAgoShift.start.setHours(8, 0, 0, 0);
      twoDaysAgoShift.end = new Date(now);
      twoDaysAgoShift.end.setDate(twoDaysAgoShift.end.getDate() - 1);
      twoDaysAgoShift.end.setHours(20, 0, 0, 0);
      
      yesterdayShift.start = new Date(now);
      yesterdayShift.start.setDate(yesterdayShift.start.getDate() - 1);
      yesterdayShift.start.setHours(20, 0, 0, 0);
      yesterdayShift.end = new Date(now);
      yesterdayShift.end.setHours(8, 0, 0, 0);
    } else if (currentHour >= 20) {
      // 当前是夜班 (20:00-次日8:00)
      twoDaysAgoShift.start = new Date(now);
      twoDaysAgoShift.start.setHours(8, 0, 0, 0);
      twoDaysAgoShift.end = new Date(now);
      twoDaysAgoShift.end.setHours(20, 0, 0, 0);
      
      yesterdayShift.start = new Date(now);
      yesterdayShift.start.setDate(yesterdayShift.start.getDate() - 1);
      yesterdayShift.start.setHours(20, 0, 0, 0);
      yesterdayShift.end = new Date(now);
      yesterdayShift.end.setHours(8, 0, 0, 0);
    } else {
      // 当前是凌晨 (0:00-8:00)
      twoDaysAgoShift.start = new Date(now);
      twoDaysAgoShift.start.setDate(twoDaysAgoShift.start.getDate() - 2);
      twoDaysAgoShift.start.setHours(8, 0, 0, 0);
      twoDaysAgoShift.end = new Date(now);
      twoDaysAgoShift.end.setDate(twoDaysAgoShift.end.getDate() - 2);
      twoDaysAgoShift.end.setHours(20, 0, 0, 0);
      
      yesterdayShift.start = new Date(now);
      yesterdayShift.start.setDate(yesterdayShift.start.getDate() - 2);
      yesterdayShift.start.setHours(20, 0, 0, 0);
      yesterdayShift.end = new Date(now);
      yesterdayShift.end.setDate(yesterdayShift.end.getDate() - 1);
      yesterdayShift.end.setHours(8, 0, 0, 0);
    }
    
    // 创建数据库连接
    const pool = await sql.connect();
    
    // 辅助函数：执行LotPassRank查询
    async function getLotPassRankData(pool, startTime, endTime, lineId, stepName) {
      const sqlQuery = `
        WITH LotPassRank AS ( 
         -- 子查询：标记每个lot在目标步骤的过站顺序（1=第一次） 
        SELECT 
         h.lot_id, 
         h.trans_time, 
	     ROW_NUMBER() OVER (PARTITION BY H.lot_id ORDER BY H.TRANS_TIME ASC) AS pass_rank 
       FROM MES_DB.MES_DB.DBO.WIP_LOT_HIS h 
       LEFT JOIN stg_mes_ras_eqp e ON h.equipment_id = e.equipment_id 
       LEFT JOIN stg_mes_ras_eqp_line el ON e.EQUIPMENT_ID = el.EQUIPMENT_ID 
       WHERE 
           h.trans_type IN ('TRACKMOVE', 'SKIPLOT') 
               AND H.STEP_NAME = @stepName 
               AND (@lineId = '' OR el.LINE_ID = @lineId) 
       ) 
       -- 统计符合条件的唯一lot数量 
       SELECT COUNT(DISTINCT lot_id) AS count 
       FROM LotPassRank 
       WHERE 
           -- 核心条件：仅统计第一次过站（pass_rank=1），且过站时间在范围内 
           pass_rank = 1 
           AND TRANS_TIME BETWEEN @startTime AND @endTime;
      `;
      
      // 转换时间格式为'YYYY-MM-DD HH:MM:SS'
      const formatToSqlDateTime = (date) => {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };
      
      const request = pool.request();
      request.input('stepName', sql.VarChar, stepName);
      request.input('lineId', sql.VarChar, lineId);
      request.input('startTime', sql.VarChar, formatToSqlDateTime(startTime));
      request.input('endTime', sql.VarChar, formatToSqlDateTime(endTime));
      
      const result = await request.query(sqlQuery);
      return result.recordset[0]?.count || 0;
    }
    
    // 查询各个班次的产量数据
    const twoDaysAgoShiftTotal = await getLotPassRankData(
      pool, 
      twoDaysAgoShift.start, 
      twoDaysAgoShift.end,
      lineId, 
      stepName
    );
    
    const yesterdayShiftTotal = await getLotPassRankData(
      pool, 
      yesterdayShift.start, 
      yesterdayShift.end,
      lineId, 
      stepName
    );
    
    const currentShiftTotal = await getLotPassRankData(
      pool, 
      timeRanges.currentShift.start, 
      timeRanges.currentShift.end,
      lineId, 
      stepName
    );
    
    // 为当前班次的所有interval添加count属性
    for (const interval of timeRanges.currentShift.intervals) {
      const count = await getLotPassRankData(
        pool, 
        interval.startTime, 
        interval.endTime,
        lineId, 
        stepName
      );
      interval.count = count;
    }
    
    // 构建返回结果 - 与DC路由完全相同的数据结构
    const result = {
      twoDaysAgoShift: {
          data: twoDaysAgoShiftTotal,
          test: `${formatDate(twoDaysAgoShift.start)}${twoDaysAgoShift.start.getHours() === 8 ? '白班' : '夜班'}`
        },
        yesterdayShift: {
          data: yesterdayShiftTotal,
          test: `${formatDate(yesterdayShift.start)}${yesterdayShift.start.getHours() === 8 ? '白班' : '夜班'}`
        },
      currentShiftTotal: currentShiftTotal,
      currentShiftIntervals: timeRanges.currentShift.intervals.map(interval => {
        const startHour = String(interval.startTime.getHours()).padStart(2, '0');
        const endHour = interval.originalEndTime ? 
          String(interval.originalEndTime.getHours()).padStart(2, '0') : 
          String(interval.startTime.getHours() + 2).padStart(2, '0');
        return {
          date: `${startHour}:00-${endHour}:00`,
          data: interval.count || 0
        };
      })
    };
    
    res.json({
      success: true,
      data: result,
      message: 'LotPassRank查询成功'
    });
  } catch (error) {
    console.error('LotPassRank查询错误:', error.message);
    res.status(500).json({
      success: false,
      message: '查询失败',
      error: error.message
    });
  }
});

module.exports = router;